const app = getApp();
var utils = require("../../utils/utils.js");
var server = require("../../utils/server.js");
var config = require("../../config.js");
var apis = require("../../utils/api.js");

Page({
  data: {
    pageSize: -1,
    pageNo: 1,
    loading: false,
    nodata: false,
    authStatus: app.globalData.userInfo.authStatus,
    photoAddress: '',
    sortingPortNumber: '',
    deliveryNoteId: '',
    dataList: [],
    image_base64: '',
    newNoteDescription: [],
    lastIndex: '',
    options: [],
    selectedOption: '',
    showSwitch: false,
    hideSwitch: true,
    isEdit: false,
    scrollTop: 0,
    showTopBtn: false,
    bgColor: '#ffffff', // 初始颜色为白色
    isPressed1: false,
    isPressed2: false
  },

  onTouchStart: function (e) {
    const index = e.currentTarget.dataset.index; // 获取当前项目的索引
    const dataList = this.data.dataList.slice(); // 复制当前数组
    dataList[index].bgColor = '#f1f1f1'; // 设置为灰色
    this.setData({
      dataList: dataList // 更新数据
    });
  },

  onTouchEnd: function (e) {
    const index = e.currentTarget.dataset.index; // 获取当前项目的索引
    const dataList = this.data.dataList.slice(); // 复制当前数组
    dataList[index].bgColor = '#ffffff'; // 恢复为白色
    this.setData({
      dataList: dataList // 更新数据
    });
  },

  handleTouchStart1() {
    this.setData({
      isPressed1: true
    });
  },

  handleTouchEnd1() {
    this.setData({
      isPressed1: false
    });
  },

  handleTouchStart2() {
    this.setData({
      isPressed2: true
    });
  },

  handleTouchEnd2() {
    this.setData({
      isPressed2: false
    });
  },

  onLoad(options) {
    console.log('详情', options)
    if (!options.value) {
      return
    }
    let params = JSON.parse(options.value);
    let newNoteDescription = options.newNoteDescription.length ? options.newNoteDescription.split(",") : [];
    this.setData({
      photoAddress: params.photoAddress,
      sortingPortNumber: params.sortingPortNumber,
      batchNumber: params.batchNumber,
      entCustomerId: params.entCustomerId,
      deliveryNoteId: params.id,
      newNoteDescription: newNoteDescription
    })
    if (params.photoAddress) {
      this.imageFind()
    }
    this.listWithPendingCount()
    this.pageMaterialInfo()

  },

  onPageScroll(e) {
    console.log(e)
    this.setData({
      scrollTop: e.scrollTop,
      // 滚动超过500px时显示置顶按钮
      showTopBtn: e.scrollTop >= 500
    })
  },

  scrollToTop() {
    wx.pageScrollTo({
      scrollTop: 0, // 滚动到顶部
      duration: 300 // 滚动动画时间（毫秒）
    })
  },

  pageMaterialInfo() {
    let _this = this;
    var prams = {
      deliveryNoteId: _this.data.deliveryNoteId,
      pageNo: 1,
      pageSize: 100
    }
    var api = apis.pageMaterialInfo;
    server.getRequest(config.xburl, api, prams,
      function (res) {
        let dataList = res.data.list
        let showSwitch = dataList[0]['materialBatchNumber'] != undefined ? true : false
        let hideSwitch = showSwitch ? false : true
        _this.setData({
          dataList: dataList,
          showSwitch: showSwitch,
          hideSwitch: hideSwitch
        });
      },
      function () {
        utils.showToast('系统繁忙，请稍后重试')
      })
  },

  imageFind() {
    let _this = this;
    let image_path = _this.data.photoAddress
    var params = {
      'image_path': image_path
    };
    utils.showLoading('数据请求中...', )
    wx.request({
      url: config.imageFindUrl,
      method: 'post',
      data: params,
      timeout: 20000,
      header: {
        'content-type': 'application/json'
      },
      success: function (res) {
        console.log(res)
        let image_base64 = res.data.image_base64
        _this.setData({
          image_base64: `data:image/jpg;base64,${image_base64}`
        })
      },
      fail: function () {
        console.log('查询送货单图片网络错误')
        utils.showToast('网络错误');
      },
    })
  },

  bindPickerChange: function (e) {
    let _this = this
    let selectedOption = _this.data.options[e.detail.value]
    let sortingPortNumber = selectedOption.substring(0, selectedOption.indexOf('号'));
    console.log('当前选择的分拣口信息', sortingPortNumber, selectedOption)
    _this.setData({
      isEdit: true,
      selectedOption: selectedOption,
      sortingPortNumber: sortingPortNumber
    })
  },

  listWithPendingCount() {
    let _this = this;
    var prams = {}
    let api = apis.listWithPendingCount;
    server.getRequest(config.xburl, api, prams,
      function (res) {
        let data = res.data
        const options = data.map(item => `${item.sortingPortNumber}号口 待分拣数量: ${item.pendingCount}`);
        const index = data.findIndex(item => item.sortingPortNumber == _this.data.sortingPortNumber);
        _this.setData({
          options: options,
          selectedOption: options[index]
        })
      },
      function () {
        utils.showToast('系统繁忙，请稍后重试')
      })
  },

  // 预览图片
  previewImage() {
    let _this = this
    wx.previewImage({
      current: _this.data.image_base64,
      urls: [_this.data.image_base64]
    });
  },

  /**
   * @description: 获取编码
   * @param {type}
   * @return:
   */
  bindBmInput: function (e) {
    let _this = this
    let index = e.currentTarget.dataset.index
    let value = e.detail.value
    if (value.length > 25) {
      utils.showToast('编码长度有误，请检查')
      return
    }
    let newItems = [..._this.data.dataList];
    newItems[index]['materialNumber'] = value;
    _this.setData({
      isEdit: true,
      dataList: newItems
    })
  },

  alertNoAction(e) {
    let _this = this
    let index = e.currentTarget.dataset.index
    let dataList = _this.data.dataList
    if(dataList[index].sortedQuantity > 0) {
      return utils.showToast('物料在分拣中，不能修改编码信息')
    }
  },

  bindWlpcInput: function (e) {
    let _this = this
    let index = e.currentTarget.dataset.index
    let value = e.detail.value
    if (value.length > 25) {
      utils.showToast('物料批次号长度有误，请检查')
      return
    }
    let newItems = [..._this.data.dataList];
    newItems[index]['materialBatchNumber'] = value;
    _this.setData({
      isEdit: true,
      dataList: newItems
    })
  },



  /**
   * @description: 获取数量
   * @param {type}
   * @return:
   */
  bindSlInput: function (e) {
    let _this = this
    let value = e.detail.value
    let index = e.currentTarget.dataset.index
    let dataList = _this.data.dataList;
    let sortedQuantity = _this.data.dataList[index].sortedQuantity;
    const reg = /^(?!0\d)\d+(\.\d+)?$/;
    // 输入数量最大不超1000
    if (!reg.test(value)) {
      utils.showToast('请您输入非零整数')
      dataList[index]['quantity'] = '';
    } else if (!(parseInt(value) > parseInt(sortedQuantity)) && parseInt(parseInt) >= 0) {
      utils.showToast(`您输入的数量需大于已分拣数，当前已分拣数量为${sortedQuantity}`)
      dataList[index]['quantity'] = '';
      return
    } else if (parseInt(value) > 1000) {
      utils.showToast('请您输入小于1000的整数')
    } else {
      dataList[index]['quantity'] = parseInt(value);
    }
    _this.setData({
      isEdit: true,
      dataList: dataList
    })
  },

  bindDelete(e) {
    let _this = this
    let index = e.currentTarget.dataset.index
    let data = _this.data.dataList[index]
    _this.onTouchEnd(e)
    if (data.sortedQuantity > 0) {
      return utils.showToast('物料在分拣中，不能删除')
    }
    wx.showModal({
      title: '温馨提示',
      content: '是否删除',
      complete: (res) => {
        if (res.cancel) {
          return
        }
        if (res.confirm) {
          let _this = this
          const index = e.currentTarget.dataset.index;
          let dataList = _this.data.dataList
          dataList.splice(index, 1)
          setTimeout(function () {
            utils.showToast('已删除')
          }, 100);
          _this.setData({
            lastIndex: '',
            isEdit: true,
            dataList: dataList
          })
        }
      }
    })
  },

  // 添加新项函数
  bindAddRow() {
    let _this = this
    let array = _this.data.dataList
    let showSwitch = _this.data.showSwitch
    let newItem = []
    let dataList = []
    if (array.length === 0) {
      if (showSwitch) {
        dataList = [{
          materialNumber: '',
          quantity: '',
          materialBatchNumber: '',
          sortingStatus: '0',
          sortedQuantity: ''
        }]
      } else {
        dataList = [{
          materialNumber: '',
          quantity: '',
          sortingStatus: '0',
          sortedQuantity: ''
        }]
      }

    } else {
      // 获取第一个元素的键
      const keys = Object.keys(array[0]);
      // 创建新对象，所有值为空字符串
      newItem = keys.reduce((obj, key) => {
        obj[key] = '';
        return obj;
      }, {});
      newItem['sortingStatus'] = '0'
      dataList = [...array, newItem]
    }
    _this.setData({
      isEdit: true,
      dataList
    })
  },

  // 创建物料信息
  bindUpdate() {
    let _this = this
    wx.showModal({
      title: '温馨提示',
      content: '是否保存并提交',
      complete: (res) => {
        if (res.confirm) {
          let dataList = _this.data.dataList;
          if (dataList.length === 0) {
            return utils.showToast('请您先录入物料信息')
          }
          for (let i = 0; i < dataList.length; i++) {
            let item = dataList[i];
            // 必填校验
            if (!item['materialNumber'] || !item['quantity']) {
              return utils.showToast('请您先将信息填写完整')
            }
            // 值合法性校验
            if (!Number.isInteger(Number(item['quantity']))) {
              return utils.showToast('数量输入有误')
            }
            item.deliveryNoteId = item.deliveryNoteId ? item.deliveryNoteId : _this.data.deliveryNoteId
            item.enterpriseId = item.enterpriseId ? item.enterpriseId : app.globalData.userInfo.entId
            item.sortingStatus = item.sortingStatus ? item.sortingStatus : 2
            dataList[i] = item
          }
          // 拼接描述
          let newNoteDescription = _this.data.newNoteDescription
          for (let i = 0; i < newNoteDescription.length; i++) {
            let item = newNoteDescription[i];
            item = "<view>" + item + "</view>"
            newNoteDescription[i] = item
          }
          let noteDescription = newNoteDescription.join('')
          let newDataList = []
          // 隐藏批次号时，上传字段全部传空
          if (_this.data.showSwitch && _this.data.hideSwitch) {
            newDataList = dataList.map(item => {
              // 如果对象中有isFLag属性，则将其值置为空
              if (item.hasOwnProperty('materialBatchNumber')) {
                return {
                  ...item,
                  materialBatchNumber: ''
                };
              }
              return item;
            });
          }

          let params = {
            "deliveryNote": {
              "entCustomerId": app.globalData.userInfo.entId,
              "id": _this.data.deliveryNoteId,
              "batchNumber": _this.data.batchNumber,
              "noteDescription": noteDescription,
              "photoAddress": _this.data.photoAddress,
              "sortingPortNumber": _this.data.sortingPortNumber
            },
            "materialInfoList": newDataList.length > 0 ? newDataList : dataList
          }
          console.log(params)
          let url = apis.updateCombined
          server.postRequest(config.xburl, url, params,
            function () {
              _this.setData({
                isEdit: false
              })
              let params = {
                type: 'ocr',
                tip: '送货单信息修改，保存成功！'
              }
              wx.navigateTo({
                url: '/pages/Result/Result?value=' + JSON.stringify(params),
              })
            },
            function () {
              utils.showToast("系统开小差了!")
            })
        }
      }
    })
  },

  toSumView() {
    let _this = this
    let dataList = _this.data.dataList
    const order = ["待处理", "未完成", '已完成', "标计完成"]
    if (dataList.length === 0) {
      return utils.showToast('请先录入物料信息')
    }
    dataList.forEach(item => {
      if (!Number.isInteger(Number(item['quantity']))) {
        return utils.showToast('数量输入有误，请输入整数型式')
      }
      if (item.sortingStatus == '1') {
        item.portStatusName = '已完成';
      } else if (item.sortingStatus == '2') {
        item.portStatusName = '未完成';
      } else if (item.sortingStatus == '99') {
        item.portStatusName = '标记完成';
      } else if (item.sortingStatus == '0') {
        item.portStatusName = '待处理';
      }
    });
    const summary = dataList.reduce((acc, curr) => {
      // 查找已有的 portStatusName 汇总对象
      let record = acc.find(item => item.portStatusName === curr.portStatusName);
      if (!record) {
        // 如果没有找到，新增记录
        record = {
          portStatusName: curr.portStatusName,
          count: 0,
          totalQuantity: 0
        };
        acc.push(record);
      }
      // 更新汇总数据
      record.count += 1; // 元素个数
      record.totalQuantity += curr.quantity; // 数量总和
      return acc;
    }, []);
    const result = utils.arrayOrderByColumn(summary, order)
    console.log(result)
    const {
      count,
      totalQuantity
    } = result.reduce((accumulator, current) => {
      return {
        count: accumulator.count + current.count,
        totalQuantity: accumulator.totalQuantity + current.totalQuantity,
      };
    }, {
      count: 0,
      totalQuantity: 0
    }); // 初始值
    let log = '';
    // 遍历数组并格式化输出
    result.forEach(item => {
      log += `${item.portStatusName}${item.count}个，共${item.totalQuantity}件\n`;
    });
    log = log + '\n' + `总计${count}个，共${totalQuantity}件\n`;
    wx.showModal({
      title: '温馨提示',
      content: log,
      showCancel: false
    })
  },

  switchChange() {
    let _this = this
    _this.setData({
      hideSwitch: !_this.data.hideSwitch
    })
  },

  markCompleted(e) {
    let _this = this;
    let dataList = _this.data.dataList
    let index = e.currentTarget.dataset.index
    let id = e.currentTarget.dataset.id
    let sortingStatus = dataList[index]['sortingStatus']
    if (sortingStatus == '1') {
      return utils.showToast('物料已完成分拣')
    }
    if (sortingStatus == '99') {
      return utils.showToast('物料已标记完成')
    }
    if (dataList[index]['materialNumber'] == '' || dataList[index]['quantity'] == '') {
      return utils.showToast('请您先将信息填写完整')
    } else {
      wx.showModal({
        title: '温馨提示',
        content: '是否标记完成',
        complete: (res) => {
          if (res.confirm) {
            let api = apis.materialMarkCompleted + '?id=' + id
            server.putRequest(config.xburl, api, {},
              function (res) {
                dataList[index]['sortingStatus'] = "99"
                utils.showToast('更新成功')
                _this.setData({
                  dataList: dataList
                })
              },
              function (err) {
                utils.showToast(err)
              })
          }
        }
      })
    }
  },

});